<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="案例标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入案例标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="分类" prop="tags">
        <el-select v-model="queryParams.labelids" multiple filterable clearable placeholder="请选择分类">
          <el-option v-for="item in labelList" :key="item.id" :label="item.label" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable>
          <el-option v-for="dict in dict.type.audit_status" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['demo:library:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['demo:library:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['demo:library:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['demo:library:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="libraryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="案例标题" align="center" prop="title" />
      <el-table-column label="分类" align="center" prop="labelManagements">
        <template slot-scope="scope">
          <el-tag v-for="item in scope.row.labelManagements" v-if="item" :key="item.id" size="small"
            style="margin: 0 2px;">{{
              item.label
            }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" prop="labels" />
      <el-table-column label="发布地址" align="center" prop="publishAddress">
        <template slot-scope="scope">
          {{ formatRegionDisplay(scope.row.publishAddress) }}
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.audit_status" :value="scope.row.auditStatus" />
        </template>
      </el-table-column>
      <el-table-column label="浏览次数" align="center" prop="viewCount" />
      <el-table-column label="喜欢数" align="center" prop="likes" />
      <el-table-column label="评论数" align="center" prop="comments" />
      <el-table-column label="收藏数" align="center" prop="collects" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_is_0_1" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.openId == null" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)" v-hasPermi="['demo:library:edit']">修改</el-button>
          <el-button v-if="scope.row.openId != null" size="mini" type="text" icon="el-icon-user-solid"
            @click="handleAudit(scope.row)" v-hasPermi="['demo:library:audit']">审核</el-button>
          <el-button v-if="scope.row.openId == null" size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)" v-hasPermi="['demo:library:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改案例库抽屉 -->
    <el-drawer :title="title" :visible.sync="open" direction="ltr" size="50%" :before-close="cancel"
      :wrapperClosable="false">
      <div class="drawer-content">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-divider content-position="left">基本信息</el-divider>
          <el-form-item label="案例标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入案例标题" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio v-for="dict in dict.type.sys_is_0_1" :key="dict.value" :label="dict.value">{{ dict.label
                }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-divider content-position="left">内容编辑</el-divider>
          <el-form-item label="案例内容">
            <el-row style="margin-bottom: 20px;">
              <el-col align="right">
                <span style="color: #E6A23C;margin-right: 20px;">保存后会覆盖其他富文本编辑器内容</span>
                编辑器：
                <el-select v-model="contentType" placeholder="请选择">
                  <el-option key="1" label="Quill富文本" value="1" />
                  <el-option key="2" label="Markdown" value="2" />
                  <!-- <el-option key="3" label="Tinymce富文本" value="3" /> -->
                </el-select>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <editor v-if="contentType === '1'" v-model="form.content" :min-height="400" />
                <CherryMarkdown ref="CherryMarkdown" v-if="contentType === '2'" :height='400' v-model='form.content'>
                </CherryMarkdown>
                <!-- <Tinymce v-if="contentType === '3'" :height='400' v-model='form.content'></Tinymce> -->
              </el-col>
            </el-row>
          </el-form-item>

          <el-divider content-position="left">分类与发布</el-divider>
          <el-form-item label="分类" prop="tags">
            <el-select v-model="form.tags" multiple filterable clearable placeholder="请选择分类" style="width: 100%;">
              <el-option v-for="item in labelList" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="自定义标签" prop="labelsArr">
            <el-select v-model="form.labelsArr" multiple filterable allow-create default-first-option clearable
              placeholder="敲击【回车】录入标签" style="width: 100%;">
            </el-select>
          </el-form-item>
          <el-form-item label="发布地址" prop="publishAddress">
            <region-cascader v-model="form.publishAddress" :multiple="false" placeholder="请选择区域" />
          </el-form-item>

          <el-divider content-position="left">媒体文件</el-divider>
          <el-form-item label="案例图片" prop="imageUrl">
            <image-upload v-model="form.imageUrl" />
          </el-form-item>
          <el-form-item label="案例视频" prop="videoUrl">
            <file-upload v-model="form.videoUrl" />
          </el-form-item>
        </el-form>
        <div class="drawer-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 审核案例库抽屉 -->
    <el-drawer :title="auditTitle" :visible.sync="auditOpen" direction="ltr" size="40%" :before-close="cancelAudit">
      <div class="drawer-content">
        <el-form ref="auditForm" :model="auditForm" :rules="auditRules" label-width="100px">
          <el-divider content-position="left">案例信息</el-divider>
          <el-form-item label="案例标题">
            <el-input v-model="auditForm.title" readonly />
          </el-form-item>
          <el-form-item label="提交部门">
            <el-input v-model="auditForm.deptName" readonly />
          </el-form-item>
          <el-divider content-position="left">内容预览</el-divider>
          <el-form-item>
            <div class="content-preview">
              <div v-html="auditForm.content" v-if="contentType === '1'"></div>
              <div v-else-if="contentType === '2'" v-html="compileMarkdown(auditForm.content)"></div>
              <div v-else>{{ auditForm.content }}</div>
            </div>
          </el-form-item>
          <el-divider content-position="left">审核信息</el-divider>
          <el-form-item label="审核状态" prop="auditStatus">
            <el-select v-model="auditForm.auditStatus" placeholder="请选择审核状态" style="width: 100%;">
              <el-option v-for="dict in dict.type.audit_status" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核意见" prop="auditOpinion">
            <el-input v-model="auditForm.auditOpinion" type="textarea" :rows="4" placeholder="请输入审核意见" maxlength="500"
              show-word-limit />
          </el-form-item>
        </el-form>
        <div class="drawer-footer">
          <el-button type="primary" @click="submitAudit">确 定</el-button>
          <el-button @click="cancelAudit">取 消</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listLibrary, getLibrary, delLibrary, addLibrary, updateLibrary } from "@/api/demo/library";
import { listLabel } from "@/api/demo/label";
import RegionCascader from "@/components/RegionCascader";
import CherryMarkdown from '@/components/CherryMarkdown'
// import Tinymce from '@/components/Tinymce'
import regionData from '@/utils/regionData'; // 导入地区数据

export default {
  name: "Library",
  dicts: ['sys_is_0_1', 'audit_status'],
  components: {
    RegionCascader,
    CherryMarkdown,
    // Tinymce
  },
  data() {
    return {
      contentType: "1",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 案例库表格数据
      libraryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 审核抽屉是否显示
      auditOpen: false,
      // 审核抽屉标题
      auditTitle: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        deptId: null,
        content: null,
        tags: null,
        publishAddress: null,
        imageUrl: null,
        videoUrl: null,
        status: null,
        viewCount: null,
      },
      // 表单参数
      form: {
        status: "1"
      },
      // 审核表单参数
      auditForm: {
        id: null,
        title: "",
        deptName: "",
        auditStatus: "",
        auditOpinion: "",
        content: ""
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: "案例标题不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择状态", trigger: "change" }
        ]
      },
      // 审核表单校验
      auditRules: {
        auditStatus: [
          { required: true, message: "请选择审核状态", trigger: "change" }
        ],
        auditOpinion: [
          { required: true, message: "请输入审核意见", trigger: "blur" },
          { min: 5, max: 500, message: "审核意见长度在 5 到 100 个字符", trigger: "blur" }
        ]
      },
      labelList: [],
      regionOptions: regionData, // 添加地区数据
    };
  },
  created() {
    this.getList();
    this.getLabelList();
  },
  methods: {
    /** 格式化区域显示 */
    formatRegionDisplay(region) {
      if (!region) return '-';

      try {
        // 如果region是字符串，尝试解析为数组
        let regionArray = region;
        if (typeof region === 'string') {
          regionArray = JSON.parse(region);
        }

        // 处理二维数组格式 [["140000","140100","140105"],["140000","140100","140106"]]
        if (Array.isArray(regionArray) && regionArray.length > 0) {
          // 判断是否是二维数组
          if (Array.isArray(regionArray[0])) {
            // 处理多个地区路径
            const regionNames = regionArray.map(path => {
              return this.getFullRegionName(path);
            });

            // 如果所有路径都相同（只显示一个），或者显示前几个用逗号分隔
            const uniqueNames = [...new Set(regionNames)];
            if (uniqueNames.length === 1) {
              return uniqueNames[0];
            } else {
              // 显示前3个，超过用等表示
              const displayNames = uniqueNames.slice(0, 3);
              return displayNames.join('、') + (uniqueNames.length > 3 ? ` 等${uniqueNames.length}个地区` : '');
            }
          } else {
            // 处理单个地区路径（一维数组）
            return this.getFullRegionName(regionArray);
          }
        }
        return '-';
      } catch (e) {
        console.error('区域数据解析失败:', e);
        // 如果解析失败，返回原始值
        return region || '-';
      }
    },

    /** 获取完整的地区名称 */
    getFullRegionName(codes) {
      if (!codes || !Array.isArray(codes) || codes.length === 0) return '';

      const names = [];
      let currentLevel = this.regionOptions;

      for (let i = 0; i < codes.length; i++) {
        const code = codes[i];
        const region = currentLevel.find(item => item.value === code);
        if (region) {
          names.push(region.label);
          currentLevel = region.children || [];
        } else {
          // 如果没有找到对应的地区，尝试直接使用编码
          names.push(code);
          break;
        }
      }

      return names.join(' / ');
    },
    /** 将Markdown内容转换为HTML */
    compileMarkdown(content) {
      if (!content) return '';
      // 这里可以使用marked.js或其他Markdown解析库
      // 简单示例，实际项目中请使用专门的Markdown解析器
      return content
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/\n/g, '<br>');
    },
    getLabelList() {
      listLabel({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.labelList = response.rows;
      });
    },
    /** 查询案例库列表 */
    getList() {
      this.loading = true;

      if (this.queryParams.labelids) {
        this.queryParams.tags = this.queryParams.labelids.join(',');
      }
      listLibrary(this.queryParams).then(response => {
        this.libraryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消审核
    cancelAudit() {
      this.auditOpen = false;
      this.resetAudit();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        content: null,
        tags: null,
        labelsArr: [],
        publishAddress: null,
        imageUrl: null,
        videoUrl: null,
        status: "1",
      };
      this.resetForm("form");
    },
    // 审核表单重置
    resetAudit() {
      this.auditForm = {
        id: null,
        title: "",
        deptName: "",
        auditStatus: "",
        auditOpinion: "",
        content: ""
      };
      this.resetForm("auditForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加案例库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getLibrary(id).then(response => {
        this.form = response.data;
        // 处理多选字段的数据格式
        if (this.form.tags && typeof this.form.tags === 'string') {
          this.form.tags = this.form.tags.split(',');

        }
        if (this.form.labels && typeof this.form.labels === 'string') {
          this.form.labelsArr = this.form.labels.split(',');
        }
        this.open = true;
        this.title = "修改案例库";
      });
    },

    /** 审核按钮操作 */
    handleAudit(row) {
      this.resetAudit();
      const id = row.id || this.ids;
      getLibrary(id).then(response => {

        this.auditForm = response.data;
        console
        this.auditOpen = true;
        this.auditTitle = "审核案例库";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理多选字段的数据格式
          const submitData = { ...this.form };
          submitData.tags = submitData.tags ? submitData.tags.join(',') : '';
          console.log('提交数据：', submitData, submitData.labelsArr);
          submitData.labels = submitData.labelsArr ? submitData.labelsArr.join(',') : '';
          submitData.publishAddress = submitData.publishAddress && submitData.publishAddress.length > 0 ? JSON.stringify(submitData.publishAddress) : '';

          if (submitData.id != null) {
            updateLibrary(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLibrary(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 提交审核 */
    submitAudit() {
      this.$refs["auditForm"].validate(valid => {
        if (valid) {
          updateLibrary(this.auditForm).then(response => {
            this.$modal.msgSuccess("审核成功");
            this.auditOpen = false;
            this.getList();
          });
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除案例库编号为"' + ids + '"的数据项？').then(function () {
        return delLibrary(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('demo/library/export', {
        ...this.queryParams
      }, `library_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.drawer-content {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
}

.drawer-footer {
  position: absolute;
  bottom: 20px;
  right: 20px;
}

.el-divider {
  margin: 30px 0 20px 0;
}

.el-form-item {
  margin-bottom: 20px;
}

.content-preview {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  max-height: 300px;
  overflow-y: auto;
  background-color: #fafafa;
}

/* 为必填项添加红色星号 */
.el-form-item.is-required .el-form-item__label:before {
  content: '*';
  color: #F56C6C;
  margin-right: 4px;
}
</style>